/*
 *所有关于Equipment类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*EquipmentService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VoL.Domain.IRepositories;
using VoL.Domain.Infrastructure;
using SkiaSharp;
using VoL.Domain.Dtos.Equipment;

namespace VoL.Domain.Services
{
    public partial class EquipmentService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IBaseRepository<Office> _officeRepo;
        private readonly IBaseRepository<WardArea> _wardAreaRepo;
        private readonly IBaseRepository<WardAreaNursingUnit> _wardAreaNursingUnitRepo;
        private readonly IBaseRepository<NursingUnit> _nursingUnitRep;
        private readonly IEquipmentRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public EquipmentService(IEquipmentRepository dbRepository,IHttpContextAccessor httpContextAccessor,IBaseRepository<Office> officeRepo,
            IBaseRepository<WardArea> wardAreaRepo,IBaseRepository<WardAreaNursingUnit> wardAreaNursingUnitRepo,IBaseRepository<NursingUnit> nursingUnitRep)
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _officeRepo = officeRepo;
            _wardAreaRepo = wardAreaRepo;
            _wardAreaNursingUnitRepo = wardAreaNursingUnitRepo;
            _nursingUnitRep = nursingUnitRep;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        public Task<WebResponseContent> GetUnitTree()
        {
            var res =new WebResponseContent();

            // 分别查询所有表数据
            var offices = _officeRepo.GetAll().ToList();
            var wardAreas = _wardAreaRepo.GetAll().ToList();
            var wardAreaNursingUnits = _wardAreaNursingUnitRepo.GetAll().ToList();
            var nursingUnits = _nursingUnitRep.GetAll().ToList();

            // 构建护理单元字典（方便快速查找）
            var nursingUnitDict = nursingUnits
                .ToDictionary(nu => nu.NursingUnitCode, nu => nu.Name);

            // 按WardAreaCode分组护理单元分配
            var nursingUnitAssignmentsByWardArea = wardAreaNursingUnits
                .GroupBy(nua => nua.WardAreaCode)
                .ToDictionary(
                    g => g.Key,
                    g => g.Select(nua =>
                        nursingUnitDict.ContainsKey(nua.NurseCode)
                            ? nursingUnitDict[nua.NurseCode]
                            : nua.NurseCode // 回退方案，使用代码作为名称
                    ).ToList()
                );

            // 按OfficeCode分组病区
            var wardAreasByOffice = wardAreas
                .GroupBy(wa => wa.OfficeCode)
                .ToDictionary(g => g.Key, g => g.ToList());

            // 构建树形结构
            var rootOffices = offices.Where(o => o.ParentDepart == 1).ToList();


            var treeNodes = rootOffices.Select(office => new OfficeTreeNodeDTO
            {
                OfficeName = office.OfficeName,
                WardAreas = BuildWardAreaTree(
                    wardAreasByOffice.GetValueOrDefault(office.OfficeCode, new List<WardArea>()),
                    nursingUnitAssignmentsByWardArea
                )
            }).ToList();

            res.OK("单元属性查询成功",treeNodes);
            return Task.FromResult(res);
        }
        private List<WardAreaTreeNodeDTO> BuildWardAreaTree(
      List<WardArea> wardAreas,
      Dictionary<string, List<string>> nursingUnitAssignmentsByWardArea)
        {
            return wardAreas.Select(wardArea => new WardAreaTreeNodeDTO
            {
                WardAreaName = wardArea.Name,
                NursingUnits = nursingUnitAssignmentsByWardArea.GetValueOrDefault(
                    wardArea.WardAreaCode,
                    new List<string>()
                )
            }).ToList();
        }
    }

    
}
